package ua.eug.robov2.schematic;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import ua.eug.robov2.schematic.chips.ChipActor;
import ua.eug.robov2.utils.Vector2i;

public class SheetMap implements Externalizable {
	
	private static final int defX = 128;
	private static final int defY = 128;
	public Vector2i size;
	
	//!!!!!!!!! first index - Y, second  - X !!!!!!
	public int[][] map;
	
	public SheetMap() {

	}

	public SheetMap(int[][] map) {
		size = new Vector2i();
		size.y = map.length;
		if (size.y > 0) 
			size.x = map[0].length;
		this.map = map;
	}
	
	public SheetMap(Vector2i size) {
		map = new int[size.y][size.x];
		this.size = size;
	}

	public void put(Vector2i pos, int index) {
		if (isValidPos(pos))
			map[pos.y][pos.x] = index;
	}
	
	public Boolean isValidPos(Vector2i pos) {
		if (pos.x < 0 || pos.y<0 ||
				pos.x >= this.size.x ||
				pos.y >= this.size.y) return false;
		return true;
	}
	
	// check if this place empty
	public Boolean check(ChipActor ca) {
		if (!ca.isFit(this)) return false;
		for (int i=0; i<ca.mapSize.x; i++)
			for (int j=0; j<ca.mapSize.y; j++) {
				if (map[j+ca.pos.y][i+ca.pos.x] != 0) return false;
			}		
		return true;
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		size = (Vector2i) in.readObject();
		map = new int[size.y][size.x];
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeObject(size);		
	}

}
